import { PreviewData } from "@/api";
import { PreviewTreeData } from "./inteface";
import _ from "lodash";

/**
 * 适配器, 使用eclipse类似的平铺合并方法
 * - $codeBaseUrl
 *    - com.xxx.xxx
 *      - XXX.java
 *    - com.xxx.yyy
 *      - yyy.java
 * - $codeBaseUrl
 *    - ...
 */
export const toTreeData = (data: PreviewData[]): PreviewTreeData[] => {
  if (_.isEmpty(data)) {
    return [];
  }
  const res: PreviewTreeData[] = [];
  const cbuGroup = _.groupBy(data, (k) => k.codeBaseUrl);
  for (const cbuKey of Object.keys(cbuGroup)) {
    const cbuValues = cbuGroup[cbuKey];
    const cbuSample = cbuValues[0];
    const cbuChildren: PreviewTreeData[] = [];
    const cbuData: PreviewTreeData = {
      key: cbuSample.codeBaseUrl,
      title: cbuSample.codeBaseUrl,
      isLeaf: false,
      children: cbuChildren,
    };
    res.push(cbuData);
    const pnGroup = _.groupBy(cbuValues, (k) => k.packageName);
    for (const pnKey of Object.keys(pnGroup)) {
      const pnValues = pnGroup[pnKey];
      const pnSample = pnValues[0];
      const pnChildren: PreviewTreeData[] = [];
      const pnData: PreviewTreeData = {
        key: `${cbuData.key}-${pnSample.packageName}`,
        title: pnSample.packageName || "(默认)",
        isLeaf: false,
        children: pnChildren,
      };
      cbuChildren.push(pnData);

      for (const leafItem of pnValues) {
        const leafData: PreviewTreeData = {
          key: leafItem.absoluteUrl,
          title: leafItem.fileName,
          isLeaf: true,
          data: leafItem,
        };
        pnChildren.push(leafData);
      }
    }
  }
  return res;
};
